package me.itsoo.artemis.framework.repository.mapper.resource;

import me.itsoo.artemis.framework.core.util.Assert;
import me.itsoo.artemis.framework.core.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * QueryResource
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/11
 */
public class QueryResource extends AbstractResource {

    private final String table;

    private final List<String> fields;

    /**
     * 首节点构造
     *
     * @param table String
     */
    private QueryResource(String table) {
        this.table = table;
        this.fields = new ArrayList<>();
    }

    /**
     * select
     *
     * @param table String
     * @return QueryResource
     */
    public static QueryResource select(String table) {
        Assert.isNotBlank(table, "'table' cannot be empty");
        return new QueryResource(table);
    }

    /**
     * add
     *
     * @param field String
     * @return QueryResource
     */
    public QueryResource add(String field) {
        Assert.isNotBlank(field, "'field' cannot be empty");
        fields.add(field);
        return this;
    }

    @Override
    public String getResourceCommand() {
        final StringJoiner result = new StringJoiner(" ");
        if (CollectionUtils.isEmpty(fields)) {
            return result.toString();
        }

        result.add("select");

        for (int i = 0, len = fields.size(), last = len - 1; i < len; i++) {
            String fn = fields.get(i);
            if (i < last) {
                fn = fn.concat(",");
            }

            result.add(fn);
        }

        result.add("from");
        result.add(table);
        return result.toString();
    }
}
